<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="配送订单号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入配送订单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="配送物流公司" prop="logisticsCompany">
        <el-input
          v-model="queryParams.logisticsCompany"
          placeholder="请输入配送物流公司"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="配送物流单号" prop="logisticsNo">
        <el-input
          v-model="queryParams.logisticsNo"
          placeholder="请输入配送物流单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="预计到货时间" prop="estimatedArrivalTime">
        <el-date-picker
          v-model="queryParams.estimatedArrivalTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择订单状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.DELIVERY_ORDER_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="配送状态" prop="deliveryStatus">
        <el-select
          v-model="queryParams.deliveryStatus"
          placeholder="请选择配送状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.DELIVERY_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="预警状态" prop="alertStatus">
        <el-select
          v-model="queryParams.alertStatus"
          placeholder="请选择预警状态"
          clearable
          class="!w-240px"
        >
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['trade:deliveryOrder:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['trade:deliveryOrder:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="isEmpty(checkedIds)"
          @click="handleDeleteBatch"
          v-hasPermi="['trade:deliveryOrder:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      row-key="id"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      :row-class-name="tableRowClassName"
      @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="主键ID" align="center" prop="id" width="100" />
      <el-table-column label="配送订单号" align="center" prop="orderNo" width="200">
        <template #default="{ row }">
          <el-link type="primary" @click="openDetail(row.id)">
            {{ row.orderNo }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="配送基地" align="center" prop="farmName" width="150" />
      <el-table-column label="配送总价" align="center" prop="totalPrice" width="120">
        <template #default="{ row }">
          <span class="text-red-500 font-bold">¥{{ row.totalPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column label="车牌号" align="center" prop="vehiclePlate" width="120" />
      <el-table-column label="配送物流公司" align="center" prop="logisticsCompany" width="150" />
      <el-table-column label="配送物流单号" align="center" prop="logisticsNo" width="180" />
      <el-table-column
        label="预计到货时间"
        align="center"
        prop="estimatedArrivalTime"
        :formatter="dateFormatter"
        width="180"
      />
      <el-table-column
        label="实际出发时间"
        align="center"
        prop="actualDepartureTime"
        :formatter="dateFormatter"
        width="180"
      />
      <el-table-column
        label="实际到达时间"
        align="center"
        prop="actualArrivalTime"
        :formatter="dateFormatter"
        width="180"
      />
      <el-table-column label="订单状态" align="center" prop="status" width="100">
        <template #default="{ row }">
          <dict-tag :type="DICT_TYPE.DELIVERY_ORDER_STATUS" :value="row.status" />
        </template>
      </el-table-column>
      <el-table-column label="预警状态" align="center" prop="alertStatus" width="120">
        <template #default="{ row }">
          <template v-if="getAlertConfig(row)">
            <el-tag
              :type="getAlertConfig(row).level === 'urgent' ? 'danger' : 'warning'"
              :effect="getAlertConfig(row).level === 'urgent' ? 'dark' : 'plain'"
            >
              <Icon
                :icon="getAlertConfig(row).level === 'urgent' ? 'ep:warning-filled' : 'ep:warning'"
                class="mr-5px"
              />
              {{ getAlertConfig(row).message }}
            </el-tag>
          </template>
          <el-tag v-else type="success">正常</el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column label="配送状态" align="center" prop="deliveryStatus" width="100">
        <template #default="{ row }">
          <dict-tag :type="DICT_TYPE.DELIVERY_STATUS" :value="row.deliveryStatus" />
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="预警状态" align="center" prop="alertStatus" width="100" />
      <el-table-column
        label="预警时间"
        align="center"
        prop="alertTime"
        :formatter="dateFormatter"
        width="180"
      /> -->
      <el-table-column label="备注信息" align="center" prop="remark" width="150" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180"
      />
      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="warning"
            @click="handleStartDelivery(scope.row)"
            v-if="scope.row.status === 0"
            v-hasPermi="['trade:deliveryOrder:update']"
          >
            配送
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['trade:deliveryOrder:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['trade:deliveryOrder:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <OrderForm ref="formRef" @success="getList" />
  <!-- 详情弹窗 -->
  <OrderDetail ref="detailRef" />
</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { useUserStore } from '@/store/modules/user'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'

import { OrderApi, OrderVO } from '@/api/mall/trade/deliveryOrder'
import { AlertConfigApi, AlertConfigVO } from '@/api/mall/trade/alertconfig'
import { InfoApi } from '@/api/farm/info'
import OrderForm from './OrderForm.vue'
import OrderDetail from './OrderDetail.vue'

/** 农场到自营门店的配送订单 列表 */
defineOptions({ name: 'DeliveryOrder' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const userStore = useUserStore() // 用户store

const loading = ref(true) // 列表的加载中
const list = ref<OrderVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数

// 预警配置列表 - 从后端读取
const alertConfigs = ref<AlertConfigVO[]>([])

// 加载预警配置
const loadAlertConfig = async () => {
  try {
    const configs = await AlertConfigApi.getEnabledAlertConfigs()
    alertConfigs.value = configs || []
    console.log('加载预警配置:', alertConfigs.value)
  } catch (e) {
    console.error('加载预警配置失败', e)
  }
}
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  orderNo: undefined,
  farmId: undefined,
  logisticsCompany: undefined,
  logisticsNo: undefined,
  estimatedArrivalTime: [],
  status: undefined,
  deliveryStatus: undefined,
  alertStatus: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await OrderApi.getOrderPage(queryParams)

    // 如果数据中有没有农场名称的项，查询农场信息来填充
    const itemsWithoutFarmName = data.list.filter((item) => item.farmId && !item.farmName)
    if (itemsWithoutFarmName.length > 0) {
      try {
        const farmList = await InfoApi.getSimpleFarmList()
        itemsWithoutFarmName.forEach((item) => {
          const farm = farmList.find((f) => f.id === item.farmId)
          if (farm) {
            item.farmName = farm.farmName
          }
        })
      } catch (error) {
        console.error('查询农场信息失败:', error)
      }
    }

    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 打开详情 */
const detailRef = ref()
const openDetail = (id: number) => {
  detailRef.value.open(id)
}

/** 配送按钮操作 */
const handleStartDelivery = async (row: OrderVO) => {
  try {
    // 确认框
    await message.confirm('确认要开始配送该订单吗？')
    // 调用更新状态接口
    await OrderApi.updateOrderStatus({
      id: row.id!,
      status: 1, // 订单状态改为配送中
      deliveryStatus: 1 // 配送状态改为配送中
    })
    message.success('配送状态已更新')
    // 刷新列表
    await getList()
  } catch (e) {
    console.error('更新配送状态失败:', e)
    message.error('更新配送状态失败，请稍后重试')
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await OrderApi.deleteOrder(id)
    message.success(t('common.delSuccess'))
    currentRow.value = {}
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除农场到自营门店的配送订单 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await OrderApi.deleteOrderList(checkedIds.value)
    checkedIds.value = []
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const checkedIds = ref<number[]>([])
const currentRow = ref<any>({})
const handleRowCheckboxChange = (records: OrderVO[]) => {
  checkedIds.value = records.map((item) => item.id).filter((id): id is number => id !== undefined)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await OrderApi.exportOrder(queryParams)
    download.excel(data, '农场到自营门店的配送订单.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 获取匹配的预警配置（返回最小小时数的匹配配置） */
const getAlertConfig = (row: OrderVO) => {
  // 只对未完成的订单进行预警（status != 2 表示未完成）
  if (row.status === 2 || !row.estimatedArrivalTime || !alertConfigs.value.length) {
    return null
  }

  const now = new Date().getTime()
  const estimatedTime = new Date(row.estimatedArrivalTime).getTime()
  const diffHours = (estimatedTime - now) / (1000 * 60 * 60)

  // 调试日志
  console.log('预警判断 - 订单号:', row.orderNo)
  console.log('当前时间:', new Date(now).toLocaleString())
  console.log('预计送达:', new Date(estimatedTime).toLocaleString())
  console.log('距离送达:', diffHours.toFixed(2), '小时')
  console.log('启用的预警配置数:', alertConfigs.value.filter((c) => c.isEnabled).length)
  console.log('预警配置列表:', alertConfigs.value)

  // 找到所有匹配的预警配置（距离送达时间小于等于配置的小时数）
  const matchedConfigs = alertConfigs.value
    .filter((config) => config.isEnabled && diffHours <= config.alertHours)
    .sort((a, b) => a.alertHours - b.alertHours) // 按小时数升序排序

  console.log('匹配到的配置数:', matchedConfigs.length, matchedConfigs)

  if (matchedConfigs.length === 0) {
    return null
  }

  // 返回最小小时数的配置（最紧急的）
  const config = matchedConfigs[0]
  return {
    message: config.configName,
    level: config.alertHours <= 2 ? 'urgent' : 'warning', // 2小时及以内视为紧急
    hours: config.alertHours,
    fullMessage: config.alertMessage
  }
}

/** 统计预警订单 */
const countAlertOrders = () => {
  const alertOrders = list.value.filter((item) => getAlertConfig(item) !== null)
  const urgentOrders = alertOrders.filter((item) => {
    const config = getAlertConfig(item)
    return config && config.level === 'urgent'
  })
  const warningOrders = alertOrders.filter((item) => {
    const config = getAlertConfig(item)
    return config && config.level === 'warning'
  })

  return {
    urgent: urgentOrders.length,
    warning: warningOrders.length,
    total: alertOrders.length
  }
}

/** 显示预警提示 */
const showAlertNotification = () => {
  const alertCount = countAlertOrders()
  if (alertCount.total > 0) {
    const content = `您有 ${alertCount.urgent} 个紧急预警订单${
      alertCount.warning > 0 ? `，${alertCount.warning} 个配送预警订单` : ''
    }，请及时处理！`
    message.notifyWarning(content)
  }
}

/** 表格行样式 */
const tableRowClassName = ({ row }: { row: OrderVO }) => {
  const alertConfig = getAlertConfig(row)
  if (alertConfig) {
    return alertConfig.level === 'urgent' ? 'urgent-alert-row' : 'warning-alert-row'
  }
  return ''
}

/** 初始化 **/
onMounted(async () => {
  // 先加载预警配置
  await loadAlertConfig()
  // 再加载列表
  await getList()
  // 显示预警提示
  showAlertNotification()
})
</script>

<style scoped lang="scss">
/* 紧急预警行样式 - 红色背景 */
:deep(.urgent-alert-row) {
  background-color: #fef0f0 !important;

  &:hover > td {
    background-color: #fde2e2 !important;
  }
}

/* 配送预警行样式 - 橙色背景 */
:deep(.warning-alert-row) {
  background-color: #fdf6ec !important;

  &:hover > td {
    background-color: #faecd8 !important;
  }
}
</style>
